/*
 * this class will be called from the variable 2activity.
 * array list bundle from the previous activity will be send here and those variables data will be shown on the graph.
 * here as soon as activity started background thread will be started and will continuously update the graph for the particular
 * variable.
 */
package com.fipl.taksar;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TableRow;
import android.widget.Toast;

import com.artfulbits.aiCharts.ChartView;
import com.artfulbits.aiCharts.Base.ChartArea;
import com.artfulbits.aiCharts.Base.ChartPoint;
import com.artfulbits.aiCharts.Base.ChartSeries;
import com.artfulbits.aiCharts.Base.ChartAxis.LabelsMode;
import com.artfulbits.aiCharts.Types.ChartTypes;
import com.fipl.parse.SelectVariableParser;

public class VariableGraph extends Activity {
	
	private ChartView chartView;
	private ChartPoint point;
	private boolean callDlgFlag = true;
	private boolean selectMonthFlag = false;
	private int monthNumber;								// will store month number
	private int currentMonth;								// will store current month
	private int currentYear;								// will store current year
	private String selectedMonth;							// will store selectedMonth
	private String dbName;									// will store db name
	private boolean running = false;
	private boolean handlerFlag = false;
	private ArrayList<Integer> indexCheckArrayList = new ArrayList<Integer>();
	private ArrayList<String> fetcha = new ArrayList<String>();
	private HashMap<Integer, ArrayList<String>> mapData = new HashMap<Integer, ArrayList<String>>();
	private String [] variable={"Temperature_1", "Temperature_2", "Temperature_3" ,"Temperature_4", 
			"Humidity_1", "Humidity_2", "Humidity_3","Humidity_4","PSTemperature_1","PSTemperature_2",
			"Diesel_1","Diesel_2",
			"Voltage_1A","Voltage_1B","Voltage_1C","Voltage_2A","Voltage_2B","Voltage_2C",
			"Voltage_3A","Voltage_3B","Voltage_3C","Voltage_4A","Voltage_4B","Voltage_4C",
			"Voltage_5A","Voltage_5B","Voltage_5C","Voltage_6A","Voltage_6B","Voltage_6C",
			"Voltage_7A","Voltage_7B","Voltage_7C","Voltage_8A","Voltage_8B","Voltage_8C",
			"Current_1A","Current_1B","Current_1C","Current_2A","Current_2B","Current_2C",
			"Current_3A","Current_3B","Current_3C","Current_4A","Current_4B","Current_4C",
			"Current_5A","Current_5B","Current_5C","Current_6A","Current_6B","Current_6C",
			"DigitalInput_1","DigitalInput_2","DigitalInput_3","DigitalInput_4","DigitalInput_5",
			"DigitalInput_6","DigitalInput_7","DigitalInput_8","DigitalInput_9","DigitalInput_10",
			"DigitalInput_11","DigitalInput_12","DigitalInput_13","DigitalInput_14","DigitalInput_15",
			"DigitalInput_16","DigitalInput_17","DigitalInput_18","DigitalInput_19","DigitalInput_20",
			"DigitalInput_21","DigitalInput_22","DigitalInput_23","DigitalInput_24","DigitalOutput_1",
			"DigitalOutput_2","DigitalOutput_3","DigitalOutput_4","DigitalOutput_5","DigitalOutput_6",
			"DigitalOutput_7","DigitalOutput_8","DigitalOutput_9","DigitalOutput_10","DigitalOutput_11",
			"DigitalOutput_12","DigitalOutput_13","DigitalOutput_14","DigitalOutput_15","DigitalOutput_16"
	};
	private String [] month = {"January", "February", "March","April","May","June","July","August","September","October","November","December"};
	private String[] monthPosition = {"01","02","03","04","05","06","07","08","09","10","11","12"};
	private SelectVariableParser parser;
	private ProgressDialog progressDialog;
	private AlertDialog.Builder builder;
	private AlertDialog alertDialog = null;
	private Thread backgroundThread;

	public void onCreate(Bundle savedInstanceState){
		super.onCreate(savedInstanceState);
		setContentView(R.layout.variablegraph);
		dbName = ((GlobalData)this.getApplicationContext()).getDbName();

		Date date = new Date();						// get the current date
		currentYear = (date.getYear()+1900);		// get the current year
		currentMonth = (date.getMonth()+1);			// get the current month	
		Bundle bundle = getIntent().getExtras();
		indexCheckArrayList.addAll(bundle.getIntegerArrayList("indexCheck"));	// get the index click from the previous activity
		callDialog();				// call the progress dialog 

	}

	public void GetData(){
		fetcha.clear();
		mapData.clear();
		Looper.prepare();
		String currentMonthString = String.valueOf(currentMonth);

		if(currentMonthString.length()==1){
			currentMonthString = "0"+currentMonthString;
		}

		if(selectMonthFlag){
			currentMonthString = selectedMonth;
		}
		Log.d("System out", "current month "+currentMonthString);
		for(int i =0; i<indexCheckArrayList.size();i++){
			parser= new SelectVariableParser(dbName,currentMonthString, String.valueOf(currentYear), variable[indexCheckArrayList.get(i)]);
			if(parser.SelectVariableData() == -1){
				Toast.makeText(getApplicationContext(), "No data downloaded !! Please Try again",Toast.LENGTH_SHORT);
//				getError();
			}else{
				mapData.put(i, parser.selectVariableParse.average);
				fetcha.addAll(parser.selectVariableParse.fecha);
			}
		}
		VariableGraph.this.handler.sendEmptyMessage(0);
		callDlgFlag = false;
	}

	public void ViewData(){
		setContentView(R.layout.historical);

		@SuppressWarnings("unused")
		ChartSeries series;
		Date[] fetchaStr = new Date[fetcha.size()];
		try{
			SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
			for(int i = 0; i<fetcha.size();i++){
				fetchaStr[i]=dateFormat.parse(fetcha.get(i));
			}
		}catch (Exception e) {
			// TODO: handle exception
			Log.d("System out", "Error date "+e.getMessage());
		}

		chartView = (ChartView)findViewById(R.id.chartView);

		ChartArea area = chartView.getAreas().get(0);
		area.getDefaultXAxis().setLabelsMode(LabelsMode.SeriesLabels);
		
		ChartSeries[] chartSeries3 = new ChartSeries[indexCheckArrayList.size()];
		for(int i=0; i<chartSeries3.length;i++){
			chartSeries3[i] = new ChartSeries(ChartTypes.Line);
			chartSeries3[i].setName(variable[indexCheckArrayList.get(i)]);
			chartSeries3[i].setShowLabel(true);

			for(int j=0;j<mapData.get(i).size();j++){
				point = chartSeries3[i].getPoints().addXY(fetchaStr[j].getDate(),Double.parseDouble(mapData.get(i).get(j)));
				if(selectMonthFlag){
					point.setAxisLabel(fetchaStr[j].getDate()+"/"+(String.valueOf(monthNumber+1))+"/"+(fetchaStr[j].getYear()+1900));
				}else{
					point.setAxisLabel(fetchaStr[j].getDate()+"/"+(fetchaStr[j].getMonth()+1)+"/"+(fetchaStr[j].getYear()+1900));
				}
			}
			
			if(indexCheckArrayList.size()==1){
				point.setLabel(variable[indexCheckArrayList.get(i)]);
			}
			chartView.getSeries().add(chartSeries3[i]);
		}

		Button monthButton = (Button)findViewById(R.id.btnTime);
		monthButton.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				selectMonthDlg();
				fetcha.clear();
				mapData.clear();
			}
		});

		Button refreshButton = (Button)findViewById(R.id.refreshBtn);
		refreshButton.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				chartView.refreshDrawableState();
			}
		});

	}

	Handler handler = new Handler(){
		@Override
		public void handleMessage(Message msg){
			progressDialog.dismiss();
			ViewData();
		}
	};

	public void callDialog(){

		this.progressDialog = ProgressDialog.show(VariableGraph.this,"Please wait", "Connecting.. Please wait..", true);

		new Thread(new Runnable(){
			public void run(){
				try{
					GetData();
				}catch (Exception e){
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}).start();
	}
	
	/*
	 * select month dialog will be called.
	 */
	public void selectMonthDlg(){

		LayoutInflater inflater = (LayoutInflater)VariableGraph.this.getSystemService(LAYOUT_INFLATER_SERVICE);
		View view = inflater.inflate(R.layout.selecttime, (ViewGroup)findViewById(R.id.mainlayout));
		builder = new AlertDialog.Builder(VariableGraph.this);
		builder.setView(view);
		builder.setTitle("Select Month");

		DatePicker datePicker = (DatePicker)view.findViewById(R.id.datePicker);
		TableRow tableRow = (TableRow)view.findViewById(R.id.row);
		Button cancelButton = (Button)view.findViewById(R.id.cancelBtn);
		Button okButton = (Button)view.findViewById(R.id.okBtn);
		tableRow.removeView(okButton);
		LinearLayout linearLayout = (LinearLayout)view.findViewById(R.id.mainlayout);
		linearLayout.removeView(datePicker);

		ListView listView = (ListView)view.findViewById(R.id.selectListView);
		listView.setMinimumWidth(200);
		listView.setAdapter(new ArrayAdapter<String>(getApplicationContext(), R.layout.simple_list_item_1,month));
		listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1,
					int arg2, long arg3) {
				// TODO Auto-generated method stub
				selectedMonth = monthPosition [arg2];
				if(Integer.valueOf(selectedMonth)>currentMonth){
					Toast.makeText(getApplicationContext(), "Please Select lower month then current month", Toast.LENGTH_SHORT).show();
				}else{
					callDlgFlag = false;
					setRunning(false);
					monthNumber = arg2;
					alertDialog.dismiss();
					selectMonthFlag = true;
					callDialog();
				}				
			}
		});

		cancelButton.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				alertDialog.dismiss();
			}
		});

		alertDialog = builder.create();
		alertDialog.show();
	}

	Handler handler2 = new Handler(){
		public void handleMessage(Message msg){
			if(!callDlgFlag){
				if(handlerFlag){
					chartView.refreshDrawableState();
				}
			}
			
		}
	};

	/*
	 * (non-Javadoc)
	 * @see android.app.Activity#onStart()
	 */
	@Override
	protected void onStart() {
		// TODO Auto-generated method stub
		super.onStart();

		Toast.makeText(this, "onStart()", Toast.LENGTH_LONG).show();
		backgroundThread = new Thread(new Runnable(){
			@Override
			public void run() {
				// TODO Auto-generated method stub
				while(running){
					try {
						GetData2();
						Thread.sleep(18000); //you can replace 300000 for 5 min, 600000 for 10 min, 900000 for 15 min
					} catch (InterruptedException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				}
			}
		});

		setRunning(true);
		backgroundThread.start();

	}

	/*
	 * (non-Javadoc)
	 * @see android.app.Activity#onStop()
	 */
	@Override
	protected void onStop() {
		// TODO Auto-generated method stub
		super.onStop();

		boolean retry = true;
		setRunning(false);

		while(retry){
			try {
				backgroundThread.join();
				retry = false;
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		Toast.makeText(this, "onStop()", Toast.LENGTH_LONG).show();
		VariableGraph.this.finish();
	}

	/*
	 * this method is called to stop background thread.
	 */
	public void stopThread(){
		boolean retry = true;
		setRunning(false);

		while(retry){
			try {
				backgroundThread.join();
				retry = false;
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		Toast.makeText(this, "onStop()", Toast.LENGTH_LONG).show();
		
		Intent intent = new Intent();
		intent.setClass(getApplicationContext(), Variable2Activity.class);
		startActivity(intent);
		
	}

	public void setRunning(boolean b){
		running = b;
	}
	
	/*
	 * this method will be called in the background 
	 */
	public void GetData2(){

		if(!callDlgFlag){

			String currentMonthString = String.valueOf(currentMonth);

			if(currentMonthString.length()==1){
				currentMonthString = "0"+currentMonthString;
			}

			if(selectMonthFlag){
				currentMonthString = selectedMonth;
			}

			for(int i =0; i<indexCheckArrayList.size();i++){
				parser= new SelectVariableParser(dbName,currentMonthString, String.valueOf(currentYear), variable[indexCheckArrayList.get(i)]);
				if(parser.SelectVariableData() == -1){
					Log.d("System out", "Json Error");
				}else{
					mapData.put(i, parser.selectVariableParse.average);
					fetcha.addAll(parser.selectVariableParse.fecha);
				}
			}
		}
		handler2.sendMessage(handler2.obtainMessage());
		handlerFlag = true;
	}
	
	/*
	 * (non-Javadoc)
	 * @see android.app.Activity#onKeyDown(int, android.view.KeyEvent)
	 */
	public boolean onKeyDown(int keyCode, KeyEvent event){
		super.onKeyDown(keyCode, event);
		if(keyCode == KeyEvent.KEYCODE_BACK){
			if( progressDialog.isShowing() ){
				progressDialog.dismiss();
			}
		}	
		return false;
	}	

	/*
	 * (non-Javadoc)
	 * @see android.app.Activity#onCreateOptionsMenu(android.view.Menu)
	 */
	public boolean onCreateOptionsMenu (Menu menu){
		MenuInflater menuInflater = getMenuInflater();
		menuInflater.inflate(R.menu.option, menu);
		return true;
	}

	/*
	 * (non-Javadoc)
	 * @see android.app.Activity#onOptionsItemSelected(android.view.MenuItem)
	 */
	public boolean onOptionsItemSelected(MenuItem menuItem){

		switch (menuItem.getItemId()) {

		case R.id.menuDb:
			((GlobalData)this.getApplicationContext()).setLoginFlag(false);
			((GlobalData)this.getApplicationContext()).setMenuNo(100);
			Intent intent = new Intent();
			intent.setClass(getApplicationContext(), ConfigurationActivity.class);
			startActivity(intent);
			break;

		case R.id.menuExit:
			VariableGraph.this.finish();
			break;
		}
		return true;
	}

}
